from django.utils.translation import gettext_lazy, gettext as _
from django.core.exceptions import ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.serializers import Serializer
from rest_framework.response import Response
from rest_framework.decorators import action
from drf_yasg.utils import swagger_auto_schema

from core import errors
from utils.paginators import NoPaginatorInspector
from apps.api.paginations import NewPageNumberPagination100
from apps.api.viewsets import NormalGenericViewSet, serializer_error_msg
from apps.app_tx_meeting import serializers
from apps.app_tx_meeting.managers import MeetingUserWrapper, tx_meeting_configs
from apps.app_tx_meeting.models import TxMeetingConfig


class PreMeetingNoticeTemplateViewSet(NormalGenericViewSet):
    permission_classes = [IsAuthenticated]
    pagination_class = NewPageNumberPagination100
    lookup_field = 'id'

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('会前通知模板配置查询'),
        paginator_inspectors=[NoPaginatorInspector],
        responses={
            200: ''''''
        }
    )
    def list(self, request, *args, **kwargs):
        """
        会前通知模板配置查询

            http code 200:
            {
                "content": "xxx"
            }
        """
        tx_meeting_configs.clear_cache()
        content = tx_meeting_configs.get(tx_meeting_configs.ConfigName.PRE_MEET_NOTICE_TEMPLATE.value)
        return Response(data={
            'content': content
        })

    @swagger_auto_schema(
        tags=['tx_meeting'],
        operation_summary=gettext_lazy('修改会前通知模板'),
        paginator_inspectors=[NoPaginatorInspector],
        responses={
            200: ''''''
        }
    )
    @action(methods=['POST'], detail=False, url_path='update', url_name='update')
    def update_template(self, request, *args, **kwargs):
        """
        修改会前通知模板配置

            * 需要管理员权限
            * 纯文本格式
            * 模板中使用格式"${key}"方式替换填充会议信息，key可选值：meeting_subject（会议主题）、meeting_time（会议时间）、
                meeting_code（腾讯会议号）、meeting_join_url（入会链接）。
            * 如果内容中你想输出1个特殊字符“$”，需要多输入1个“$”对其进行转义，即“$$”。

            http code 200:
            {
                "content": "xxx"
            }
        """
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid(raise_exception=False):
            msg = serializer_error_msg(serializer.errors)
            return self.exception_response(exc=errors.InvalidArgument(message=msg))

        ur_wrapper = MeetingUserWrapper(user=request.user)
        if not ur_wrapper.is_active_user():
            return self.exception_response(
                errors.AccessDenied(message=_('你的账号状态无效')))

        if not ur_wrapper.is_admin():
            return self.exception_response(
                errors.AccessDenied(message=_('你没有管理员权限')))

        content = serializer.data['content']
        cfg_name = tx_meeting_configs.ConfigName.PRE_MEET_NOTICE_TEMPLATE.value

        try:
            obj = TxMeetingConfig(name=cfg_name, value=content)
            obj.clean()
        except ValidationError as exc:
            return self.exception_response(exc=errors.InvalidArgument(message=exc.messages[0]))

        tx_meeting_configs.set(name=cfg_name, value=content)
        tx_meeting_configs.clear_cache()
        content = tx_meeting_configs.get(cfg_name)
        return Response(data={
            'content': content
        })

    def get_serializer_class(self):
        if self.action == 'update_template':
            return serializers.ContentSerializer

        return Serializer
